home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 364 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.1 KB

  1. Path: news.umbc.edu!not-for-mail
  2. From: schlein@umbc.edu (Jonas J. Schlein)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: start array at k, not 0
  5. Date: 4 Jan 1996 15:27:34 -0500
  6. Organization: University of Maryland Baltimore County
  7. Message-ID: <4chd7m$n54@umbc9.umbc.edu>
  8. References: <Pine.OSF.3.91.960104095358.22268B-100000@io.UWinnipeg.ca>
  9. NNTP-Posting-Host: f-umbc9.umbc.edu
  10. NNTP-Posting-User: schlein
  11.  
  12. Bill Simpson  <wsimpson@uwinnipeg.ca> wrote:
  13. |> I have come up with the following 2 methods that allow one to talk about
  14. |> an array that starts at element k rather than 0.  E.g. 10 element array
  15. |> y[k] to y[k+10].  Both seem to work.  Is this illusory?  Is one of the
  16. |> 2 ways better (or a way I haven't mentioned)?
  17. |> 
  18. |> These programs set up y[5] to y[14].
  19. |> 
  20. |> Thanks very much for any comments.
  21.  
  22. Let me guess...You didn't read the FAQ?
  23.  
  24. |> /*method 1*/
  25. |> #include <stdio.h>
  26. |> 
  27. |> int main(void)
  28. |>  {
  29. |>  int i, x[10];
  30. |>  int* y;
  31. |>  int offset=5;  /*ie 1st index at 5, y[5]-y[14] */
  32. |>  y=x-offset;
  33. |> 
  34. |>  printf("offset=%d\n",offset);
  35. |> 
  36. |>  for (i=offset;i<10+offset;i++)
  37. |>         {
  38. |>         y[i]=i;
  39. |>         printf("%d\n",y[i]);
  40. |>         }
  41. |>  return 0;
  42. |>  }
  43.  
  44. This corresponds roughly to the FAQ question 6.17. It often works, but
  45. is not guaranteed to work and does not correspond to the C standard.
  46.  
  47. |> /*method 2*/
  48. |> #include <stdio.h>
  49. |> #include <stdlib.h>
  50. |> 
  51. |> int main(void)
  52. |>  {
  53. |>  int i;
  54. |>  int* y;
  55. |>  int offset=5;  
  56. |>  int n=10;       
  57. |>  y=malloc(n*sizeof(int));
  58. |> 
  59. |>  printf("offset=%d\n",offset);
  60. |> 
  61. |>  for (i=offset;i<n+offset;i++)
  62. |>         {
  63. |>         y[i]=i;
  64. |>         printf("%d\n",y[i]);
  65. |>         }
  66. |>  return 0;
  67. |>  }
  68.  
  69. I chalk this up to either dumb luck or else your compiler allocates memory
  70. in some kind of block sizes which allows *this* particular program
  71. using *this* particular offset to work. You have allocated a dynamic
  72. block of storage that can be referenced only from y[0] to y[9]. Any
  73. indices other than these are in the realm of undefined behavior.
  74. -- 
  75. "If it wasn't for C, we would be using BASI, PASAL, and OBOL."
  76.  
  77. Jonas J. Schlein  (schlein@gl.umbc.edu)
  78.